//
//  AppDelegate.m
//  WeiWeiHaircut
//
//  Created by 超群 on 15/10/8.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "AppDelegate.h"
#import "WWLoginViewController.h"
#import "APService.h"
#import <AlipaySDK/AlipaySDK.h>
#import "OpenUDID.h"
#import "WXApiManager.h"
//微信支付用到的一些key
/**
 *  微信开放平台申请得到的 appid, 需要同时添加在 URL schema
 */
NSString * const WXAppId = @"wx4842ea968be119cf";//公众帐号身份的唯一标识。
/**
 *  微信公众平台商户模块生成的ID
 */
NSString * const WXAppKey = @"F216F22FB05FB67567E219FA3DD4F3BD"; // API密钥

NSString * const WXPartnerId = @"1297418401";//商户身份的标识

NSString * const WXAppSecret = @"0dccecf770b0b7a12d0d561d1a27f181";//公众帐号支付请求中用于加密的密钥Key，可验证商户唯一身份，PaySignKey对应于支付场景中的appKey值。

NSString * const WXPartnerKey = @"";//商户权限密钥Key。

@interface AppDelegate () <BMKGeneralDelegate>
{
    BMKMapManager* _mapManager;
    
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    WWLoginViewController* loginVC = [[WWLoginViewController alloc]initWithNibName:nil bundle:nil];
    UINavigationController* navVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
    navVC.navigationBar.tintColor = [UIColor whiteColor];
    [navVC.navigationBar setBackgroundImage:[UIImage imageNamed:@"QZNavgationImage.png"] forBarMetrics:UIBarMetricsDefault];
    
    self.window.rootViewController = navVC;
    [self.window makeKeyAndVisible];

    //适配iOS8(地图)
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8) {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        CLLocationManager  *locationManager = [[CLLocationManager alloc] init];
        //获取授权认证
        //[locationManager requestAlwaysAuthorization];
        [locationManager requestWhenInUseAuthorization];
    }
    //self.locService = [[BMKLocationService alloc]init];
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"7OGtWPMfMqL1HcKcPs0giI40"  generalDelegate:self];
    if (!ret) {
        NSLog(@"地图初始化失败");
    }
    
    // Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
    // Required
    [APService setupWithOption:launchOptions];
    //设置别名
    [APService setAlias:[QZUserInfo userId] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
    
    //微信注册appID
    [WXApi registerApp:@"wx4842ea968be119cf" withDescription:@"VVCut"];
    //AppSecret：0dccecf770b0b7a12d0d561d1a27f181
    //http://www.vvgufen.com
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    return YES;
}

- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias
{
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    [BMKMapView willBackGround];
}

//已经进入前台
- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    [BMKMapView didForeGround];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [APService registerDeviceToken:deviceToken];
    NSLog(@"registrationID  = %@",[APService registrationID]);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    // Required
    [APService handleRemoteNotification:userInfo];

    NSLog(@"%@",userInfo);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        // 前台
//        [[iToast makeText:userInfo[@"aps"][@"alert"]] show];
        [[[UIAlertView alloc] initWithTitle:@"通知" message:userInfo[@"aps"][@"alert"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"取消",@"确认", nil] show];
        
    }else{
        //后台
        
    }
     NSLog(@"%@",userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    NSLog(@"%@",url.host);
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            NSLog(@"result = %@",resultDic);
            if ([resultDic[@"resultStatus"] integerValue] == 9000) {

                [[iToast makeText:@"支付成功"] show];
            }else{
                [[iToast makeText:@"支付失败"] show];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"支付成功" object:nil];
        }];
    }else{
        BOOL isSour = [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
        if (isSour) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"支付成功" object:nil];
        }
        return  isSour;
    }
    
    return YES;
}
@end
